package cn.wind.xboot.module.web.controller;

import cn.wind.xboot.logic.entity.Accessid;
import cn.wind.xboot.logic.service.IAccessidService;
import cn.wind.xboot.module.web.utils.HttpUtils;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 *获取AccessId的Controller(本接口供app端调用)
 * @author WangHao
 * @date 2019-03-13
 */
@Slf4j
@RequestMapping("accessId")
@Controller
public class AccessIdController {
    @Autowired
    private IAccessidService accessidService;

    private static String host = "http://47.99.170.25/NNQuery.php?";
    private static String path = "AccessID=000&Act=login";

    /**
     * 获取AccessId
     */
    @RequestMapping("/getAccessId")
    @ResponseBody
    public Object getAccessId(Integer type, HttpServletResponse httpServletResponse){
        //允许跨域
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, String> map = Maps.newHashMap();
        Accessid accessid = accessidService.selectByType(type);
        if (accessid != null){
            map.put("AccessID",accessid.getAccessId());
            return map;
        }else {
            //数据库还没有accessid信息
            Map<String, String> querys = new HashMap<String, String>();
            Map<String,String> bodys = new HashMap<String,String>( );
            String method = "POST";
            bodys.put("UsrName","hopdata_test");
            bodys.put("UsrPwd","0.01qaz");
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            try {
                HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
                String str = EntityUtils.toString(response.getEntity());
                String AccessID = JSONObject.fromObject(str).getString("AccessID");
                map.put("AccessID", AccessID);
                //将AccessID信息保存到数据库
                Accessid a = new Accessid();
                a.setType( type );
                a.setAccessId(AccessID);
                accessidService.saveOrUpdate(a);
                return map;
            } catch (Exception e) {
                //throw new RuntimeException( e );
                map.put("AccessID","获取失败!");
                return map;
            }
        }
    }

}
